package com.lw.contoll;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lw.ReturnInfo;
import com.lw.config.mybatis.page.Page;
import com.lw.config.mybatis.page.PageRequest;
import com.lw.entity.GoodsInfo;
import com.lw.mapper.GoodsMapper;
import com.lw.util.FileUploadUtil;
import com.lw.vo.GoodsInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/goods")
public class GoodsInfoController {

    @Autowired
    private GoodsMapper goodsMapper;

    @GetMapping ("/findGoodsById/{id}")
    @ResponseBody
    public ReturnInfo findGoodsById(@PathVariable("id")int id){
        GoodsInfoVo goodsInfoVo = this.goodsMapper.findInfoById(id);
        return ReturnInfo.returnSuccessInfo(goodsInfoVo);
    }

    @PostMapping ("/findGoodsListByPage")
    @ResponseBody
    public ReturnInfo findGoodsListByPage(@RequestBody GoodsInfo bookInfo, HttpServletRequest request){
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        PageRequest pageRequest = new PageRequest(Integer.parseInt(page),Integer.parseInt(size));

        Page<GoodsInfoVo> pageData = this.goodsMapper.findGoodsListByPage(bookInfo,pageRequest);
        return ReturnInfo.returnSuccessInfo(pageData);
    }

    @PostMapping ("/addGoodsInfo")
    @ResponseBody
    public ReturnInfo addGoodsInfo(GoodsInfo goodsInfo,HttpServletRequest request){
        Map<String,String> fileUploadMap = FileUploadUtil.uploadFiles(request);
        //将文件路径组装成json格式
        String image = getImageJson(fileUploadMap);
        goodsInfo.setImage(image);

        goodsInfo.setGoods_code(GoodsInfo.generateGoodsCode());

        if(StringUtils.isEmpty(goodsInfo.getGoods_description())){
            goodsInfo.setGoods_description(null);
        }
        if(StringUtils.isEmpty(goodsInfo.getTags())){
            goodsInfo.setTags(null);
        }

        this.goodsMapper.addGoodsInfo(goodsInfo);
        return ReturnInfo.returnSuccessInfo();
    }

    private String getImageJson(Map<String,String> fileUploadMap){
        String image = null;
        if(fileUploadMap!=null&&fileUploadMap.size()>0){
            List<ImageInfo> imageInfos = new ArrayList<>();
            Iterator<String> iterator = fileUploadMap.keySet().iterator();
            while (iterator.hasNext()){
                String name = iterator.next();
                String path = fileUploadMap.get(name);
                ImageInfo imageInfo = new ImageInfo(name,path);
                imageInfos.add(imageInfo);
            }
            image = JSON.toJSONString(imageInfos);
        }
        return image;
    }

    @PostMapping ("/updateGoodsInfo")
    @ResponseBody
    public ReturnInfo updateGoodsInfo(GoodsInfoVo goodsInfo,HttpServletRequest request){
        if(goodsInfo.getChangeImage()==true){
            Map<String,String> fileUploadMap = FileUploadUtil.uploadFiles(request);
            //将文件路径组装成json格式
            String image = getImageJson(fileUploadMap);
            goodsInfo.setImage(image);
        }

        if(StringUtils.isEmpty(goodsInfo.getGoods_description())){
            goodsInfo.setGoods_description(null);
        }
        if(StringUtils.isEmpty(goodsInfo.getTags())){
            goodsInfo.setTags(null);
        }

        this.goodsMapper.updateGoodsInfo(goodsInfo);
        return ReturnInfo.returnSuccessInfo();
    }

    @GetMapping ("/showImage")
    public void showImage(@RequestParam("imagePath") String imagePath, HttpServletResponse response){
        String checkPath = System.getProperty("user.dir") + "/" + "files";
        if(!imagePath.startsWith(checkPath)){//不是指定的文件路径，不可以返回文件
            return;
        }

        try(FileInputStream fis = new FileInputStream(imagePath)) {
            OutputStream os = response.getOutputStream();

            byte[] buff = new byte[1024];

            while(fis.read(buff)!=-1){
                os.write(buff,0,buff.length);
            }
        } catch (IOException e) {
            log.error("",e);
        }
    }
}

class ImageInfo{
    public String name;
    public String path;

    public ImageInfo(String name,String path){
        this.name = name;
        this.path = path;
    }
}

